package com.sky.interceptor;

import com.sky.context.BaseContext;
import com.sky.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author wangqi
 * @date 2024/1/3 09:54
 */
@Configuration
public class UserTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //如果不是动态资源，直接放行
        if (!(handler instanceof HandlerMethod)){
            return true;
        }

        //获取token
        //authentication: eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MDQyNTM3MzMsInVzZXJJZCI6NX0.KAAftBothz9w60qGo8puxMbfQdjR4a9fVpg2CdEowhA
        String token = request.getHeader("authentication");
        try {
            Claims claims = JwtUtil.parseJWT("weixin_token", token);
            //获取用户id
            long userId = Long.parseLong(claims.get("userId").toString());
            //把用户id存储到ThreadLocal当中
            BaseContext.setCurrentId(userId);
            return true; //放行
        } catch (Exception e) {
            //解析token失败，不放行
            response.setStatus(401);
            return false;
        }
    }
}
